//
//  CloudViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2016/11/25.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "CloudViewController.h"
#import "magazineTableViewCell.h"
#import "AreaBookTableViewCell.h"
#import "SubVideoCollectionViewCell.h"
#import "SearchViewController.h"
#import "CloudSecondViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "ZRTableView.h"
#import "MagazineDetailViewController.h"
#import "BookDetailViewController.h"
#import "MagazineDetailViewController.h"

#define buttonW ((SCREEN_W - WidthScale(40)) / 4 + WidthScale(20))

@interface CloudViewController () <UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate, SearchViewDelegate>

/** 导航条 */
@property (nonatomic, strong) UIImageView * navBar;
/** 电子书按钮 */
@property (nonatomic, strong) UIButton * bookButton;
/** 视频按钮 */
@property (nonatomic, strong) UIButton * videoButton;
/** 期刊按钮 */
@property (nonatomic, strong) UIButton * magazineButton;
/** 少儿按钮 */
@property (nonatomic, strong) UIButton * kidsButton;
/** 电子书列表 */
@property (nonatomic, strong) ZRTableView * bookTableView;
/** 视频列表 */
@property (nonatomic, strong) ZRTableView * videoTableView;
/** 视频分类列表 */
@property (nonatomic, strong) UICollectionView * videoCollectionView;
/** 视频分类列表布局 */
@property (nonatomic, strong) UICollectionViewFlowLayout * videoFlowLayout;
/** 期刊列表 */
@property (nonatomic, strong) ZRTableView * magazineTableView;
/** 期刊列表父视图 */
@property (nonatomic, strong) UIScrollView * magazineBackScrollView;
/** 少儿列表 */
@property (nonatomic, strong) ZRTableView * kidsTableView;
/** 电子书数据源 */
@property (nonatomic, strong) NSMutableArray * bookArr;
/** 视频数据源 */
@property (nonatomic, strong) NSMutableArray * videoArr;
/** 期刊一级数据源 */
@property (nonatomic, strong) NSMutableArray * magazineArr;
/** 期刊二级数据源 */
@property (nonatomic, strong) NSMutableArray * magazineSource;
/** 泛舟书海数据源 */
@property (nonatomic, strong) NSMutableArray * kidsArr1;
/** 漫步刊林数据源 */
@property (nonatomic, strong) NSMutableArray * kidsArr2;
/** 奇妙影院数据源 */
@property (nonatomic, strong) NSMutableArray * kidsArr3;
/** 视频播放器 */
@property (nonatomic, strong) MPMoviePlayerViewController * player;
//杂志分类按钮父视图
@property (nonatomic, strong) UIView * backViewButtons;
@property (nonatomic, strong) NSMutableArray * buttonArr;
@property (nonatomic, strong) UIScrollView * buttonScrollView;
/** 搜索视图控制器 */
@property (nonatomic, strong) SearchViewController * searchVC;

@end

@implementation CloudViewController

- (SearchViewController *)searchVC{
    if (!_searchVC) {
        _searchVC = [[SearchViewController alloc] init];
        _searchVC.delegate = self;
    }
    return _searchVC;
}

- (MPMoviePlayerViewController *)player{
    if (!_player) {
        _player = [[MPMoviePlayerViewController alloc] init];
        _player.moviePlayer.shouldAutoplay = YES;
        _player.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;

    }
    return _player;
}

- (UIScrollView *)magazineBackScrollView{
    if (!_magazineBackScrollView) {
        _magazineBackScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.backViewButtons.frame), SCREEN_W, SCREEN_H - CGRectGetMaxY(self.backViewButtons.frame) - 49)];
        _magazineBackScrollView.delegate = self;
        _magazineBackScrollView.pagingEnabled = YES;
        _magazineBackScrollView.showsHorizontalScrollIndicator = NO;
        _magazineBackScrollView.hidden = YES;
        _magazineBackScrollView.contentSize = CGSizeMake(SCREEN_W * self.magazineArr.count, _magazineBackScrollView.frame.size.height);
        
        for (int i = 0; i < self.magazineArr.count; i ++) {
            self.magazineTableView = [[ZRTableView alloc] initWithFrame:CGRectMake(i * SCREEN_W, 0, SCREEN_W, _magazineBackScrollView.frame.size.height)];
            self.magazineTableView.delegate = self;
            self.magazineTableView.dataSource = self;
            self.magazineTableView.backgroundColor = COLOR_LIGHTBGCOLOR;
            self.magazineTableView.tableFooterView = [UIView new];
            self.magazineTableView.rowHeight = SCREEN_W / 2.6;
            self.magazineTableView.tag = 10 + i;
            self.magazineTableView.dataArr = [NSMutableArray array];
            
            [_magazineBackScrollView addSubview:self.magazineTableView];
        }
        
    }
    return _magazineBackScrollView;
}

- (UIView *)backViewButtons{
    if (!_backViewButtons) {
        _backViewButtons = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.navBar.frame), SCREEN_W, HeightScale(30))];
        _backViewButtons.hidden = YES;
        
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, HeightScale(30))];
        self.buttonScrollView = scrollView;
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.backgroundColor = COLOR_LIGHTBGCOLOR;
        [_backViewButtons addSubview:scrollView];
        
        CGFloat tagButtonX, tagButtonW;
        tagButtonX = WidthScale(8);
        NSMutableArray *buttonArr = [NSMutableArray array];

        self.buttonArr = buttonArr;
        for (int i = 0; i < self.magazineArr.count; i ++) {
            tagButtonW = [self.magazineArr[i][@"name"] length] * 18;
            UIButton *tagButton = [[UIButton alloc] initWithFrame:CGRectMake(tagButtonX, HeightScale(2), WidthScale(tagButtonW), HeightScale(26))];
            tagButtonX += tagButtonW + WidthScale(8);
            [tagButton setTitle:self.magazineArr[i][@"name"] forState:UIControlStateNormal];
            [tagButton setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
            [tagButton setBackgroundImage:ImageNamed(@"buttonBack_d") forState:UIControlStateNormal];
            [tagButton setBackgroundImage:ImageNamed(@"buttonBack") forState:UIControlStateSelected];
            tagButton.titleLabel.font = FONTSIZE(14);
            tagButton.layer.cornerRadius = WidthScale(6);
            tagButton.layer.masksToBounds = YES;
            tagButton.titleLabel.adjustsFontSizeToFitWidth = YES;
            tagButton.tag = 10 + i;
            [scrollView addSubview:tagButton];
            scrollView.contentSize = CGSizeMake(tagButtonX, HeightScale(30));
            [buttonArr addObject:tagButton];
            
            [scrollView addSubview:tagButton];
            
            if (i == 0) {
                tagButton.selected = YES;
            }
        
            __weak typeof(self)weakSelf = self;
            [tagButton initWithBlock:^(UIButton *button) {
                DLog(@"%@", button.titleLabel.text);
                for (UIButton *deButton in buttonArr) {
                    deButton.selected = NO;
                }
                if (!button.selected) {
                    button.selected = YES;
                }
                
                [UIView animateWithDuration:0.2 animations:^{
                    
                    weakSelf.magazineBackScrollView.contentOffset = CGPointMake(SCREEN_W * i, 0);
                    ZRTableView *tableView = (ZRTableView *)[weakSelf.magazineBackScrollView viewWithTag:10 + i];
                    if (tableView.loadedData == NO) {
                        [weakSelf requestMagazineSecond:i];
                        tableView.loadedData = YES;
                    }
                    
                    if (scrollView.contentSize.width > SCREEN_W) {
                        if (button.center.x > SCREEN_W / 2 && ((scrollView.contentSize.width - button.center.x) > SCREEN_W / 2)) {
                            scrollView.contentOffset = CGPointMake(button.center.x - SCREEN_W / 2, 0);
                        } else if (button.center.x > SCREEN_W / 2 && (scrollView.contentSize.width - button.center.x) < SCREEN_W / 2) {
                            scrollView.contentOffset = CGPointMake(scrollView.contentSize.width - SCREEN_W, 0);
                        } else {
                            scrollView.contentOffset = CGPointMake(0, 0);
                        }
                    }
                }];
                
                
            } for:UIControlEventTouchUpInside];
        }

        
    }
    return _backViewButtons;
}


- (NSMutableArray *)kidsArr3{
    if (!_kidsArr3) {
        _kidsArr3 = [NSMutableArray array];
    }
    return _kidsArr3;
}

- (NSMutableArray *)kidsArr2{
    if (!_kidsArr2) {
        _kidsArr2 = [NSMutableArray array];
    }
    return _kidsArr2;
}

- (NSMutableArray *)kidsArr1{
    if (!_kidsArr1) {
        _kidsArr1 = [NSMutableArray array];
    }
    return _kidsArr1;
}

- (UICollectionViewFlowLayout *)videoFlowLayout{
    if (!_videoFlowLayout) {
        _videoFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        _videoFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;;
    }
    return _videoFlowLayout;
}

- (NSMutableArray *)magazineArr{
    if (!_magazineArr) {
        _magazineArr = [NSMutableArray array];
    }
    return _magazineArr;
}

- (NSMutableArray *)videoArr{
    if (!_videoArr) {
        _videoArr = [NSMutableArray array];
    }
    return _videoArr;
}

- (NSMutableArray *)bookArr{
    if (!_bookArr) {
        _bookArr = [NSMutableArray array];
    }
    return _bookArr;
}

- (ZRTableView *)kidsTableView{
    if (!_kidsTableView) {
        _kidsTableView = [[ZRTableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.navBar.frame) - 0.5, SCREEN_W, SCREEN_H - self.navBar.frame.size.height - 49 + 0.5 - HeightScale(10)) style:UITableViewStylePlain];
        _kidsTableView.delegate = self;
        _kidsTableView.dataSource = self;
        _kidsTableView.backgroundColor = COLOR_LIGHTBGCOLOR;
        _kidsTableView.tableFooterView = [UIView new];
        _kidsTableView.rowHeight = _kidsTableView.frame.size.height / 3;
        _kidsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _kidsTableView.bounces = NO;
        _kidsTableView.hidden = YES;
    }
    return _kidsTableView;
}

- (ZRTableView *)videoTableView{
    if (!_videoTableView) {
        _videoTableView = [[ZRTableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.navBar.frame) - 0.5, SCREEN_W, SCREEN_H - self.navBar.frame.size.height - 49 + 0.5) style:UITableViewStylePlain];
        _videoTableView.delegate = self;
        _videoTableView.dataSource = self;
        _videoTableView.backgroundColor = COLOR_DEEPBGCOLOR;
        _videoTableView.rowHeight = SCREEN_W / 1.10;
        _videoTableView.tableFooterView = [UIView new];
        _videoTableView.hidden = YES;
        _videoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _videoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestVideo)];
    }
    return _videoTableView;
}

- (ZRTableView *)bookTableView{
    if (!_bookTableView) {
        _bookTableView = [[ZRTableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.navBar.frame) - 0.5, SCREEN_W, SCREEN_H - self.navBar.frame.size.height - 49 + 0.5) style:UITableViewStylePlain];
        _bookTableView.delegate = self;
        _bookTableView.dataSource = self;
        _bookTableView.backgroundColor = COLOR_LIGHTBGCOLOR;
        _bookTableView.tableFooterView = [UIView new];
        _bookTableView.rowHeight = SCREEN_W / 3.35;
        _bookTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _bookTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestBook)];
    }
    return _bookTableView;
}

- (UIButton *)bookButton{
    if (!_bookButton) {
        _bookButton = [[UIButton alloc] initWithFrame:CGRectMake(WidthScale(20), 64, buttonW, HeightScale(36))];
        [_bookButton setTitle:@"电子书" forState:UIControlStateNormal];
        [_bookButton setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
        [_bookButton setTitleColor:COLOR_GREEN forState:UIControlStateSelected];
        _bookButton.titleLabel.font = FONTSIZE(16);
        _bookButton.titleEdgeInsets = UIEdgeInsetsMake(HeightScale(3), 0, -HeightScale(3), 0);
        [_bookButton setBackgroundImage:ImageNamed(@"yunyueduxuanzhong") forState:UIControlStateSelected];
        [_bookButton setBackgroundImage:ImageNamed(@"yunyueduxuanzhong") forState:UIControlStateHighlighted];
        _bookButton.selected = YES;
        __weak typeof(self)weakSelf = self;
        [_bookButton initWithBlock:^(UIButton * bookButton) {
            DLog(@"电子书");
            weakSelf.videoButton.selected = weakSelf.magazineButton.selected = weakSelf.kidsButton.selected = NO;
            weakSelf.videoTableView.hidden = weakSelf.magazineBackScrollView.hidden = weakSelf.backViewButtons.hidden = weakSelf.kidsTableView.hidden = YES;
            weakSelf.bookTableView.hidden = NO;
            if (!bookButton.selected) {
                bookButton.selected = YES;
            }
        } for:UIControlEventTouchUpInside];
    }
    return _bookButton;
}

- (UIButton *)videoButton{
    if (!_videoButton) {
        _videoButton = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.bookButton.frame) - WidthScale(20 * 4 / 3), self.bookButton.frame.origin.y, buttonW, self.bookButton.frame.size.height)];
        [_videoButton setTitle:@"视频" forState:UIControlStateNormal];
        [_videoButton setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
        [_videoButton setTitleColor:COLOR_GREEN forState:UIControlStateSelected];
        _videoButton.titleLabel.font = FONTSIZE(16);
        _videoButton.titleEdgeInsets = UIEdgeInsetsMake(HeightScale(3), 0, -HeightScale(3), 0);
        [_videoButton setBackgroundImage:ImageNamed(@"yunyueduxuanzhong") forState:UIControlStateSelected];
        [_videoButton setBackgroundImage:ImageNamed(@"yunyueduxuanzhong") forState:UIControlStateHighlighted];
        __weak typeof(self)weakSelf = self;
        [_videoButton initWithBlock:^(UIButton * videoButton) {
            DLog(@"视频");
            weakSelf.bookButton.selected = weakSelf.magazineButton.selected = weakSelf.kidsButton.selected = NO;
            weakSelf.bookTableView.hidden = weakSelf.magazineBackScrollView.hidden  = weakSelf.backViewButtons.hidden = weakSelf.kidsTableView.hidden = YES;
            weakSelf.videoTableView.hidden = NO;
            if (!videoButton.selected) {
                videoButton.selected = YES;
            }
        } for:UIControlEventTouchUpInside];
    }
    return _videoButton;
}

- (UIButton *)magazineButton{
    if (!_magazineButton) {
        _magazineButton = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.videoButton.frame) - WidthScale(20 * 4 / 3), self.bookButton.frame.origin.y, buttonW, self.bookButton.frame.size.height)];
        [_magazineButton setTitle:@"期刊" forState:UIControlStateNormal];
        [_magazineButton setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
        [_magazineButton setTitleColor:COLOR_GREEN forState:UIControlStateSelected];
        _magazineButton.titleLabel.font = FONTSIZE(16);
        _magazineButton.titleEdgeInsets = UIEdgeInsetsMake(HeightScale(3), 0, -HeightScale(3), 0);
        [_magazineButton setBackgroundImage:ImageNamed(@"yunyueduxuanzhong") forState:UIControlStateSelected];
        [_magazineButton setBackgroundImage:ImageNamed(@"yunyueduxuanzhong") forState:UIControlStateHighlighted];
        __weak typeof(self)weakSelf = self;
        [_magazineButton initWithBlock:^(UIButton * magazineButton) {
            DLog(@"期刊");
            weakSelf.bookButton.selected = weakSelf.videoButton.selected = weakSelf.kidsButton.selected = NO;
            weakSelf.bookTableView.hidden = weakSelf.videoTableView.hidden = weakSelf.kidsTableView.hidden = YES;
            weakSelf.magazineBackScrollView.hidden = weakSelf.backViewButtons.hidden = NO;
            if (!magazineButton.selected) {
                magazineButton.selected = YES;
            }
        } for:UIControlEventTouchUpInside];
    }
    return _magazineButton;
}

- (UIButton *)kidsButton{
    if (!_kidsButton) {
        _kidsButton = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.magazineButton.frame) - WidthScale(20 * 4 / 3), self.bookButton.frame.origin.y, buttonW, self.bookButton.frame.size.height)];
        [_kidsButton setTitle:@"少儿" forState:UIControlStateNormal];
        [_kidsButton setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
        [_kidsButton setTitleColor:COLOR_GREEN forState:UIControlStateSelected];
        _kidsButton.titleLabel.font = FONTSIZE(16);
        _kidsButton.titleEdgeInsets = UIEdgeInsetsMake(HeightScale(3), 0, -HeightScale(3), 0);
        [_kidsButton setBackgroundImage:ImageNamed(@"yunyueduxuanzhong") forState:UIControlStateSelected];
        [_kidsButton setBackgroundImage:ImageNamed(@"yunyueduxuanzhong") forState:UIControlStateHighlighted];
        __weak typeof(self)weakSelf = self;
        [_kidsButton initWithBlock:^(UIButton *kidsButton) {
            DLog(@"少儿");
            weakSelf.bookButton.selected = weakSelf.videoButton.selected = weakSelf.magazineButton.selected = NO;
            weakSelf.bookTableView.hidden = weakSelf.videoTableView.hidden = weakSelf.backViewButtons.hidden = weakSelf.magazineBackScrollView.hidden = YES;
            weakSelf.kidsTableView.hidden = NO;
            if (!kidsButton.selected) {
                kidsButton.selected = YES;
            }
        } for:UIControlEventTouchUpInside];
    }
    return _kidsButton;
}

- (UIImageView *)navBar{
    if (!_navBar) {
        _navBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 64 + HeightScale((36 + 15)))];
        _navBar.image = ImageNamed(@"daohangtiao");
        _navBar.userInteractionEnabled = YES;
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.navBar.frame) - HeightScale(15), SCREEN_W, HeightScale(15))];
        imageView.image = ImageNamed(@"yuanjiao");
        
        [_navBar addSubview:imageView];
        
        
        [_navBar addSubview:self.bookButton];
        [_navBar addSubview:self.videoButton];
        [_navBar addSubview:self.magazineButton];
        [_navBar addSubview:self.kidsButton];
        
    }
    return _navBar;
}

#pragma mark - lify cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = COLOR_LIGHTBGCOLOR;;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.view addSubview:self.navBar];
    
    [self.view addSubview:self.bookTableView];
    [self.view addSubview:self.videoTableView];
    
    [self.view addSubview:self.kidsTableView];
    
    //设置搜索按钮
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[ImageNamed(@"search") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(searchButtonClicked:)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    [self requestBook];
    
    [self requestVideo];
    
    [self requestMagazine];
    
    [self requestKids1];
    
    [self requestKids2];
    
    [self requestKids3];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinished) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestAll) name:@"loginSuccess" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestAll) name:@"logoutSuccess" object:nil];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [UIView animateWithDuration:0.1 animations:^{
        [AppDelegate shareDelegate].tabBar.customBar.center = CGPointMake(SCREEN_W / 2, SCREEN_H - [AppDelegate shareDelegate].tabBar.customBar.frame.size.height / 2);
    }];
    
    [Tool setNavigationBarType:self];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

#pragma mark - MPMoviePlayerPlaybackDidFinishNotification Method

- (void)videoFinished{
    DLog(@"停止播放");
    if (self.player) {
        self.player = nil;
    }
}

- (void)noMoreVideos{
    
    for (UIView *subView in self.player.view.subviews) {
        DLog(@"%@", subView);
        for (UIView *subview in subView.subviews) {
            DLog(@"subView %@", subview);
            for (UIView *subView2 in subview.subviews) {
                for (UIView *subview3 in subView2.subviews) {
                    for (UIView *subview4 in subview3.subviews) {
                        for (UIView *subview5 in subview4.subviews) {
                            if ([subview5 isKindOfClass:[UIButton class]]) {
                                DLog(@"%@", subview5);
                                if (subview5.frame.size.width == 32) {
                                    UIButton *button = (UIButton *)subview5;
                                    [button removeTarget:nil
                                                  action:NULL
                                        forControlEvents:UIControlEventAllEvents];
                                    [button initWithBlock:^(id obj) {
                                        [ZRProgressHUD showMsgWithoutView:@"没有更多了"];
                                    } for:UIControlEventTouchUpInside];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

#pragma mark - UITableViewDelegate & UITableViewDataSource Methods

- (NSInteger)tableView:(ZRTableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:self.bookTableView]) {
        return self.bookArr.count;
    } else if ([tableView isEqual:self.videoTableView]) {
        return self.videoArr.count;
    } else if ([tableView isEqual:self.kidsTableView]) {
        return 3;
    } else {
        return tableView.dataArr.count;
    }
}

- (UITableViewCell *)tableView:(ZRTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.bookTableView]) {
        
        static NSString *cellID = @"bookCell";
        AreaBookTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[AreaBookTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        NSString *titleStr = [NSString string];
        for (NSDictionary *dic in self.bookArr[indexPath.row][@"secondaryCategory"]) {
            titleStr = [titleStr stringByAppendingFormat:@" / %@", dic[@"name"]];
        }
        
        cell.titleLabel.text = [titleStr substringFromIndex:3];
        cell.label.text = self.bookArr[indexPath.row][@"stairCategory"][@"name"];
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", KHostAddress, self.bookArr[indexPath.row][@"stairCategory"][@"coverimagefile"]]] placeholderImage:ImageNamed(@"placeholdershipin")];
        return cell;

    } else if ([tableView isEqual:self.videoTableView]) {
        
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, HeightScale(15), WidthScale(3.5), HeightScale(14))];
        imageView.image = ImageNamed(@"矩形-75-拷贝-2");
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + WidthScale(15), 0, WidthScale(100), HeightScale(44))];
        titleLabel.text = self.videoArr[indexPath.row][@"stairCategory"][@"name"];
        titleLabel.font = FONTSIZE(17);
        titleLabel.textColor = COLOR_FONTBLACK;
        
        UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(54), 0, WidthScale(44), HeightScale(44))];
        [moreButton setImage:ImageNamed(@"more") forState:UIControlStateNormal];
            __weak typeof(self)weakSelf = self;
        [moreButton initWithBlock:^(id obj) {
            DLog(@"%@更多", weakSelf.videoArr[indexPath.row][@"stairCategory"][@"name"]);
            CloudSecondViewController *secondVC = [[CloudSecondViewController alloc] init];
            secondVC.dataArr = weakSelf.videoArr[indexPath.row][@"secondaryCategory"];
            secondVC.resourceType = 2;
            [weakSelf.navigationController pushViewController:secondVC animated:YES];
        } for:UIControlEventTouchUpInside];
        
        UICollectionView *videoCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, HeightScale(44), SCREEN_W, SCREEN_W / 1.15 - HeightScale(44)) collectionViewLayout:self.videoFlowLayout];
        self.videoCollectionView = videoCollectionView;
        videoCollectionView.delegate = self;
        videoCollectionView.dataSource = self;
        videoCollectionView.tag = indexPath.row + 10;
        videoCollectionView.backgroundColor = COLOR_LIGHTBGCOLOR;
        [videoCollectionView registerClass:[SubVideoCollectionViewCell class] forCellWithReuseIdentifier:@"videoCell"];

        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_W / 1.10 - HeightScale(10), SCREEN_W, HeightScale(10))];
        footerView.backgroundColor = COLOR_DEEPBGCOLOR;
        
        [cell.contentView addSubview:moreButton];
        
        [cell.contentView addSubview:titleLabel];
        
        [cell.contentView addSubview:imageView];
        
        [cell.contentView addSubview:videoCollectionView];
        
        [cell.contentView addSubview:footerView];
        
        cell.contentView.backgroundColor = COLOR_LIGHTBGCOLOR;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
            
    }  else if ([tableView isEqual:self.kidsTableView]){
        NSArray *imageArr = @[@"fanzhoushuhai", @"manbukanlin", @"qimiaoyingyuan"];
        
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(5), HeightScale(20), SCREEN_W - WidthScale(10), self.kidsTableView.frame.size.height / 3 - HeightScale(20))];
        imageView.image = ImageNamed(imageArr[indexPath.row]);
        
        cell.backgroundColor = COLOR_LIGHTBGCOLOR;
        
        [cell.contentView addSubview:imageView];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    } else {
        
        static NSString *cellID = @"magazineCell";
        MagazineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[MagazineTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }

        
        
        cell.titleLabel.text = [NSString stringWithFormat:@"%@", tableView.dataArr[indexPath.row][@"name"]];
        cell.descLabel.text = tableView.dataArr[indexPath.row][@"summarytext"];
        
        cell.timeLabel.text = tableView.dataArr[indexPath.row][@"publishTime"];
        
        NSString *coverimgpath = [NSString stringWithFormat:@"%@%@", KHostAddress, tableView.dataArr[indexPath.row][@"coverimgpath"]];
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:coverimgpath] placeholderImage:ImageNamed(@"placeholdershuji")];
        
        return cell;
        
    }
}

- (void)tableView:(ZRTableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DLog(@"index = %ld", indexPath.row);
    
    if ([tableView isEqual:self.bookTableView]) {
        CloudSecondViewController *secondVC = [[CloudSecondViewController alloc] init];
        secondVC.dataArr = self.bookArr[indexPath.row][@"secondaryCategory"];
        secondVC.resourceType = 1;
        [self.navigationController pushViewController:secondVC animated:YES];
    } else if ([tableView isEqual:self.videoTableView]) {
        DLog(@"null");
    } else if ([tableView isEqual:self.kidsTableView]) {
        CloudSecondViewController *secondVC = [[CloudSecondViewController alloc] init];
        if (indexPath.row == 0) {
            secondVC.dataArr = self.kidsArr1;
            secondVC.resourceType = 7;
        } else if (indexPath.row == 1) {
            secondVC.dataArr = self.kidsArr2;
            secondVC.resourceType = 8;
        } else {
            secondVC.dataArr = self.kidsArr3;
            secondVC.resourceType = 9;
        }
        [self.navigationController pushViewController:secondVC animated:YES];
    } else {
        //期刊
        MagazineDetailViewController *magazineDetailVC = [[MagazineDetailViewController alloc] init];
        magazineDetailVC.magazineDic = tableView.dataArr[indexPath.row];
        [self.navigationController pushViewController:magazineDetailVC animated:YES];
    }
}

#pragma mark - UICollectionDelegate & UICollectionViewDataSource Methods

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if ([self.videoArr[collectionView.tag - 10][@"videos"] isKindOfClass:[NSDictionary class]]) {
        NSArray *tempArr = self.videoArr[collectionView.tag - 10][@"videos"][@"items"];
        return tempArr.count;
    } else {
        return 0;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SubVideoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"videoCell" forIndexPath:indexPath];
    NSDictionary *dataDic = self.videoArr[collectionView.tag - 10][@"videos"][@"items"][indexPath.row];
    [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", KHostAddress, dataDic[@"coverImageFile"]]] placeholderImage:ImageNamed(@"placeholdershipin")];
    cell.titleLabel.text = [NSString stringWithFormat:@"【%@】", dataDic[@"name"]];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(WidthScale(190), HeightScale(144));
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return WidthScale(10);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return HeightScale(15);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(HeightScale(0), WidthScale(10), HeightScale(0), WidthScale(10));
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    NSUInteger index = collectionView.tag - 10;
    DLog(@"播放视频");
    if ([self.videoArr[index][@"videos"][@"items"][indexPath.row][@"filePath"] isKindOfClass:[NSNull class]]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"视频地址不存在" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    } else {
        NSString *url = [NSString stringWithFormat:@"%@%@", KHostAddress, self.videoArr[index][@"videos"][@"items"][indexPath.row][@"filePath"]];
        self.player.moviePlayer.contentURL = [NSURL URLWithString:url];
        [self presentViewController:self.player animated:YES completion:^{
            [self requestHistory:indexPath ID:self.videoArr[index][@"videos"][@"items"][indexPath.row][@"did"]];
            [self requestStatistics:indexPath ID:self.videoArr[index][@"videos"][@"items"][indexPath.row][@"id"]];
            [self requestAddShelfOfVideo:self.videoArr[index][@"video"][@"items"][indexPath.row][@"id"]];
            [self noMoreVideos];
        }];
    }
}

#pragma mark - UIScrollViewDelegate Method

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([scrollView isEqual:self.magazineBackScrollView]) {
        NSInteger index = scrollView.contentOffset.x / SCREEN_W;
        DLog(@"减速停止 %ld", index);
        
        ZRTableView *tableView = (ZRTableView *)[self.magazineBackScrollView viewWithTag:10 + index];
        if (tableView.loadedData == NO) {
            [self requestMagazineSecond:index];
            tableView.loadedData = YES;
        }
        
        UIButton *button = (UIButton *)[self.backViewButtons viewWithTag:10 + index];
        for (UIButton *tempButton in self.buttonArr) {
            tempButton.selected = NO;
        }
        button.selected = YES;
        
        if (self.magazineBackScrollView.contentSize.width > SCREEN_W) {
            [UIView animateWithDuration:0.2 animations:^{
                if (button.center.x > SCREEN_W / 2 && ((self.self.buttonScrollView.contentSize.width - button.center.x) > SCREEN_W / 2)) {
                    self.buttonScrollView.contentOffset = CGPointMake(button.center.x - SCREEN_W / 2, 0);
                } else if (button.center.x > SCREEN_W / 2 && (self.buttonScrollView.contentSize.width - button.center.x) < SCREEN_W / 2) {
                    self.buttonScrollView.contentOffset = CGPointMake(self.buttonScrollView.contentSize.width - SCREEN_W, 0);
                } else {
                    self.buttonScrollView.contentOffset = CGPointMake(0, 0);
                }
            }];
        }
    }
}

#pragma mark - 点击事件

- (void)searchButtonClicked:(UIBarButtonItem *)barButtonItem{
    DLog(@"搜索");
    [self presentViewController:self.searchVC animated:NO completion:nil];
}

- (void)resultDetail:(NSInteger)type dataDic:(NSDictionary *)dic{
    if (type == 1) {//书籍
        BookDetailViewController *bookDetailVC = [[BookDetailViewController alloc] init];
        bookDetailVC.bookDic = dic;
        [self.navigationController pushViewController:bookDetailVC animated:YES];
    } else if (type == 4) {//期刊
        MagazineDetailViewController *magazineDetailVC = [[MagazineDetailViewController alloc] init];
        magazineDetailVC.magazineDic = dic;
        [self.navigationController pushViewController:magazineDetailVC animated:YES];
    } else {
        
        if ([dic[@"filePath"] isKindOfClass:[NSNull class]]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"视频地址不存在" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        } else {
            NSString *url = [NSString stringWithFormat:@"%@%@", KHostAddress, dic[@"filePath"]];
            self.player.moviePlayer.contentURL = [NSURL URLWithString:url];
            [self presentViewController:self.player animated:YES completion:^{
                [self requestHistory:nil ID:dic[@"did"]];
                [self requestStatistics:nil ID:@"id"];
                [self requestAddShelfOfVideo:@"id"];
                [self noMoreVideos];
            }];
        }
    }
}

#pragma mark - data request

- (void)requestBook{
    NSString *URL = [NSString stringWithFormat:KgetCategory, KHostAddress, @(1), KOrganizationID];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"获取电子书分类成功");
            [self.bookArr removeAllObjects];
            [self.bookArr addObjectsFromArray:responseObject[@"data"]];
            
            [self.bookTableView reloadData];
            
            [self.bookTableView.mj_header endRefreshing];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
        [self.bookTableView.mj_header endRefreshing];
    }];
}

- (void)requestVideo{
    NSString *URL = [NSString stringWithFormat:KgetCategory, KHostAddress, @(2),  KOrganizationID];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"获取视频分类成功");
            [self.videoArr removeAllObjects];
            [self.videoArr addObjectsFromArray:responseObject[@"data"]];
            
            [self.videoTableView reloadData];
            
            [self.videoTableView.mj_header endRefreshing];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
        [self.videoTableView.mj_header endRefreshing];
    }];
}

- (void)requestMagazine{
    NSString *URL = [NSString stringWithFormat:KgetCategory, KHostAddress, @(4), KOrganizationID];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"获取期刊分类成功");
            [self.magazineArr removeAllObjects];
            [self.magazineArr addObjectsFromArray:responseObject[@"data"]];

            [self.magazineBackScrollView removeFromSuperview];
            self.magazineBackScrollView = nil;
            [self.backViewButtons removeFromSuperview];
            self.backViewButtons = nil;
            
            [self.view addSubview:self.magazineBackScrollView];
            [self.view addSubview:self.backViewButtons];
            
            [self requestMagazineSecond:0];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}


- (void)requestMagazineSecond:(NSInteger)index{
    NSString *URL = [NSString stringWithFormat:KgetMagazineByClick, KHostAddress, KOrganizationID, @(1), self.magazineArr[index][@"id"], @(1)];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
            self.magazineSource = [NSMutableArray arrayWithArray:responseObject[@"data"][@"items"]];
            
            ZRTableView *tableView = (ZRTableView *)[self.magazineBackScrollView viewWithTag:10 + index];
            tableView.dataArr = self.magazineSource;
            tableView.loadedData = YES;
            [tableView reloadData];
        } else {
            ZRTableView *tableView = (ZRTableView *)[self.magazineBackScrollView viewWithTag:10 + index];
            [tableView.dataArr removeAllObjects];
            [tableView reloadData];
        }

    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

- (void)requestKids1{
    NSString *URL = [NSString stringWithFormat:KgetCategory, KHostAddress, @(7), KOrganizationID];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"获取泛舟书海成功");
            [self.kidsArr1 removeAllObjects];
            [self.kidsArr1 addObjectsFromArray:responseObject[@"data"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

- (void)requestKids2{
    NSString *URL = [NSString stringWithFormat:KgetCategory, KHostAddress, @(9), KOrganizationID];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"获取奇妙影院成功");
            [self.kidsArr2 removeAllObjects];
            [self.kidsArr2 addObjectsFromArray:responseObject[@"data"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

- (void)requestKids3{
    NSString *URL = [NSString stringWithFormat:KgetCategory, KHostAddress, @(8), KOrganizationID];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"获取漫步刊林成功");
            [self.kidsArr3 removeAllObjects];
            [self.kidsArr3 addObjectsFromArray:responseObject[@"data"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 添加浏览历史(视频) */
- (void)requestHistory:(NSIndexPath *)indexPath ID:(NSString *)ID{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        NSString *URL = [NSString stringWithFormat:KaddHistory, KHostAddress, ID, @(2), KOrganizationID, [AppDelegate shareDelegate].userModel.userId];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            DLog(@"添加浏览历史");
        } failure:^(NSError *error) {
            DLog(@"添加浏览历史失败");
        }];
    }
}

/** 添加统计 */
- (void)requestStatistics:(NSIndexPath *)indexPath ID:(NSString *)ID{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        //1、图书；2、视频；3、音频；4、期刊杂志5、县域视频6、资讯
        NSString *URL = [NSString stringWithFormat:Kstatistics, KHostAddress, KCurrentIP, [AppDelegate shareDelegate].userModel.userId, KOrganizationID, @(2), ID];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加统计成功");
            } else {
                DLog(@"添加统计失败");
            }
        } failure:^(NSError *error) {
            DLog(@"%@", error);
        }];
    }
}

/** 视频添加到书架 */
- (void)requestAddShelfOfVideo:(NSString *)ID{
    if ([AppDelegate shareDelegate].userModel) {
        NSString *URL = [NSString stringWithFormat:KaddShelf, KHostAddress, ID, @(2), KOrganizationID, [AppDelegate shareDelegate].userModel.userId];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加书架成功");
            } else {
                DLog(@"添加书架失败");
            }
            
            
        } failure:^(NSError *error) {
            DLog(@"添加书架失败");
        }];
    }
}

- (void)requestAll{
    [self requestBook];
    [self requestVideo];
    [self requestMagazine];
    [self requestKids1];
    [self requestKids2];
    [self requestKids3];
}

@end
